package com.example.snakefinal;

import android.content.Context;
import android.graphics.Point;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class FoodFactory {

    FoodFactory() {
    }

    public void createFood(List<Food> foodList, int score, Context context, int size, List<Snake> snakes) {
        Point point = new Point(Const.MAP_W, Const.MAP_H);
        ArrayList<Point> takenSpawns = new ArrayList<>();
        for (int i = 0; i < foodList.size(); i++) {
            takenSpawns.add(foodList.get(i).getLocation());
        }
        for (Snake snake : snakes) {
            takenSpawns.addAll(snake.getSegmentLocations());
        }
        for (int i = foodList.size(); i < score / 50 + 1; i++) {
            if (i > 5) {
                break;
            }
            createRandomFood(foodList, score, context, size, takenSpawns, point);
        }
    }

    private void createRandomFood(List<Food> foodList, int score, Context context, int size, ArrayList<Point> takenSpawns, Point point) {
        Random rand = new Random();
        int food = rand.nextInt(6) + 1;
        switch (food) {
            case 1:
                foodList.add(new Apple(context, findSpawn(takenSpawns, point.x, point.y), size));
                break;
            case 2:
                foodList.add(new Banana(context, findSpawn(takenSpawns, point.x, point.y), size));
                break;
            case 3:
                foodList.add(new Raspberry(context, findSpawn(takenSpawns, point.x, point.y), size));
                break;
            case 4:
                foodList.add(new GoldenApple(context, findSpawn(takenSpawns, point.x, point.y), size));
                break;
            case 5:
                foodList.add(new BadApple(context, findSpawn(takenSpawns, point.x, point.y), size));
                break;
            case 6:
                if (score > 100) {
                    foodList.add(new Bomb(context, findSpawn(takenSpawns, point.x, point.y), size));
                }
                createRandomFood(foodList, score, context, size, takenSpawns, point);
                break;

            default:
                break;
        }
    }

    public Point findSpawn(ArrayList<Point> takenSpawns, int x, int y) {
        Point spawn = new Point();
        Random random = new Random();
        spawn.x = (random.nextInt(x - Const.FOOD_SIZE * 2) + Const.FOOD_SIZE);
        spawn.y = (random.nextInt(y - Const.FOOD_SIZE * 2) + Const.FOOD_SIZE);
        for (int i = 0; i < takenSpawns.size(); i++) {
            if (takenSpawns.size() > 100) {
                return spawn;
            }
            if (Snake.checkBound(spawn, takenSpawns.get(i))) {
                return findSpawn(takenSpawns, x, y);
            }
        }
        return spawn;
    }
}
